<template>
    <view class="group-select" v-if="showDrawer">
        <view class="mark" @click="closeFuc"></view>
        <view class="drawer">
            <view class="down" @click="closeFuc">
                <view class="down-btn"></view>
            </view>
            <view class="drawer-search">
                <image class="left-icon" src="@/static/images/search_black.png"> </image>
                <input v-model="keywords" @input="searchFuc" :placeholder="selectType != 1 ? '搜索电梯所属部门' : '搜索部门电梯关联责任人'"
                    placeholder-style="color:#ccc" />
                <view class="clear" @click.stop="clearKeywords" v-if="keywords.length">
                    <uni-icons color="#999999" type="clear" />
                </view>
            </view>
            <view class="base-line"></view>
            <view class="drawer-content">
                <view v-if="selectType == 1" class="raido-item" @click="chooseSelectNull">
                    <uni-icons color="#0091ff" v-if="seletNull" style="margin-right:4rpx" type="checkbox-filled" />
                    <uni-icons color="#ccc" v-else style="margin-right:4rpx" type="circle" />

                    未设置责任人
                </view>
                <view v-if="selectType == 1" class="drawer-content-title">
                    选择责任人
                </view>

                <view v-if="tree.length">
                    <groupTree :keywords="keywords" :selectType="selectType" v-for="item in tree" :selectIds="selectIds"
                        :selectGroup="selectGroup" :item="item" :key="item.id" :defaultProps="defaultProps"></groupTree>
                </view>

                <view v-else class="empty">
                    <view class="circle">
                        <image src="@/static/images/emptyS.png"></image>
                    </view>
                    <view class="title">
                        暂无搜索结果
                    </view>
                </view>
            </view>
            <view class="footer-btns">
                <view class="reSet" @click.stop="handleReset">重置</view>
                <view class="submit" @click.stop="submit"> 确定 <text v-if="selectArr.length">(已选{{
                    selectArr.length
                }}{{ selectType== 1 ? '人' : '个部门' }})</text> </view>
            </view>
        </view>

    </view>
</template>
<script>
import { getMembers, getGroups } from '@/apis/building.js';
export default {
	data() {
		return {
			showDrawer: false,
			focusState: false, // 默认不获取焦点
			keywords: '',
			tree: [],// 当前展示的树
			data: [],// 数据源
			selectIds: '',
			selectGroup: '',
			seletNull: false,// 是否选中未设置责任人,

			selectType: 1,// 类型：1人或2部门
			selectArr: [],// 选中id列表
		};
	},
	provide() {
		return {
			defaultProps: this.defaultProps,
			onClickItem: this.onClickItem
		};
	},
	props: {

		showState: {
			type: Boolean,
			default: true
		},

		defaultProps: {
			type: Object,
			default: () => {
				return {
					id: 'id',
					children: 'children',
					label: 'title'
				};
			}
		},
	},
	created() {
		this.selectArr = [];
	},
	methods: {
		closeFuc() {
			this.showDrawer = false;
			this.$emit('closed', false);
		},
		// 完成
		submit() {
			this.$emit('submit', {
				selectType: this.selectType,// 2选中部门 1选中人
				selectArr: this.selectArr, // id 列表
				seletNull: this.seletNull // 是否选中未设置责任人
			});
			this.closeFuc();
		},
		// 初始化数据
		initData(res) {
			this.selectType = res.selectType;
			this.selectArr = JSON.parse(JSON.stringify(res.selectArr || '[]'));
			// this.selectArr= ["1411852793154682881" ,"1524710724538531841"]
			this.seletNull = res.seletNull;
			this.keywords = '';
			this.data = [];
			this.tree = [];
			this.getList();
			this.showDrawer = true;
		},

		clearKeywords() {
			this.keywords = '';
			this.searchFuc({
				detail: {
					value: ''
				}
			});
		},
		// 重置
		handleReset() {
			this.keywords = '';
			this.selectArr = [];
			this.seletNull = false;
			this.tree = JSON.parse(JSON.stringify(this.data));
			this.setTreeData(this.tree);
			if (this.selectType == 1) {
				// 人

				this.setHalfStatus(this.tree);
			}
		},
		// 搜索
		searchFuc(res) { 
			let key = res.detail.value;
			this.tree = this.filterTree(JSON.parse(JSON.stringify(this.data)), key);
			this.setTreeData(this.tree);
		},
		// 过滤符合关键词的子树
		filterTree(nodes, query) {
			// 条件就是节点的title过滤关键字
			let predicate = (node) => {
				return node.title.includes(query) || query == '' || this.selectArr.indexOf(node.id) != -1;
			};

			// 结束递归的条件
			if (!(nodes && nodes.length)) {
				return [];
			}
			let newChildren = [];
			for (let node of nodes) {
				if (node.children && node.children.length) {
					node.show = true;
				}

				// 一、带父节点     以下两个条件任何一个成立，当前节点都应该加入到新子节点集中
				// 1. 子孙节点中存在符合条件的，即 subs 数组中有值
				// 2. 自己本身符合条件
				let subs = this.filterTree(node.children, query);
				if (predicate(node)) {
					newChildren.push(node);
				} else if (subs && subs.length) {
					node.children = subs;

					newChildren.push(node);
				}

				// 二、不带父节点     以下只需要考虑自身的节点满足条件即可,不用带上父节点
				// if (predicate(node)) {
				// 	newChildren.push(node);
				// 	node.children = this.filterTree(node.children, query);
				// } else {
				// 	newChildren.push(...this.filterTree(node.children, query));
				// }
			}
			return newChildren.length ? newChildren : [];
		},
		// 更新树的选中情况
		setTreeData(array) {
			if (this.selectType == 1) {
				// 选人
				for (let i = 0; i < array.length; i++) {
					if (this.keywords.length && array[i].children) {
						array[i].show = true;
					}

					if (this.selectArr.indexOf(array[i].id) != -1) {
						array[i].choosed = true;
					} else {
						array[i].choosed = false;
					} 
					if (array[i].children) {
						this.setTreeData(array[i].children);
					}
				}
			} else {
				// 选组
				for (let i = 0; i < array.length; i++) {
					if (this.selectArr.indexOf(array[i].id) != -1) {
						array[i].choosed = true;
					} else {
						array[i].choosed = false;
					} 
					if (array[i].children) {
						this.setTreeData(array[i].children);
					}
				}
			}
		},

		chooseSelectNull() {
			this.seletNull = !this.seletNull;
			if (this.seletNull == true) {
				this.clearAllChild(this.tree);
				this.selectArr = [];
			} 
		},
		// 渲染半选方法
		setHalfStatus(list) {
			let half = 0;
			for (let i = 0; i < list.length; i++) {
				if (list[i].children && list[i].children.length) {
					let hnum = this.setHalfStatus(list[i].children); 
					if (hnum == 0) {
						list[i].choosed = false;
						list[i].half = false;
					}
					if (hnum > 0 && hnum < list[i].children.length) {
						list[i].choosed = false;
						list[i].half = true;
					}
					if (hnum == list[i].children.length && hnum > 0) {
						list[i].choosed = true;
						list[i].half = false;
					}
				}
				if (list[i].choosed || list[i].half) {
					half++;
				}
			}
			return half;
		},

		// 点击组查询并对子集批量操作-人情况
		selectFater(e) {
			let point = this.findNode(e.id, this.tree);
			if (e.choosed) {
				// 已全选 清除子节点
				point.choosed = false;
				this.clearAllChild(point.children || []);
			} else {
				// 全选
				point.choosed = true;
				this.selectAllChild(point.children || []);
			}
			return;
		},

		// 子集全部清除
		clearAllChild(array) {
			for (let i = 0; i < array.length; i++) {
				array[i].choosed = false;
				array[i].half = false;
				let idx = this.selectArr.indexOf(array[i].id);
				if (idx != -1) {
					this.selectArr.splice(idx, 1);
				}
				if (array[i].children) {
					this.clearAllChild(array[i].children);
				}
			}
		},

		// 子集全选
		selectAllChild(array) {
			for (let i = 0; i < array.length; i++) {
				array[i].choosed = true;
				if (this.selectArr.indexOf(array[i].id) == -1 && array[i].type != 1) {
					this.selectArr.push(array[i].id);
				}
				if (array[i].children) {
					this.selectAllChild(array[i].children);
				}
			}
		},

		// 查找节点
		findNode(id, list) {
			if (!list) {
				return false;
			}
			for (let i = 0; i < list.length; i++) {
				if (list[i].id == id) {
					return list[i];
				} else {
					let child = this.findNode(id, list[i].children);
					if (child) {
						return child;
					}
				}
			}
			return false;
		},

		// 点击某一项
		onClickItem(e) {
			// 点击当前项目
			if (this.selectType == 1) {
				this.seletNull = false;
				// 选人
				if (e.type == 1) {
					// 点击了组
					this.selectFater(e);
				} else {
					// 点击了人
					let node = this.findNode(e.id, this.tree);
					let idx = this.selectArr.indexOf(e.id);
					if (idx == -1) {
						node.choosed = true;
						this.selectArr.push(e.id);
					} else {
						node.choosed = false;
						this.selectArr.splice(idx, 1);
					}
				}

				this.setHalfStatus(this.tree);
			} else {
				// 选组
				let node = this.findNode(e.id, this.tree);
				let idx = this.selectArr.indexOf(e.id);
				if (idx == -1) {
					node.choosed = true;
					this.selectArr.push(e.id);
				} else {
					node.choosed = false;
					this.selectArr.splice(idx, 1);
				}
			}
			// console.log(this.tree, this.selectArr, e, 'onClickItem')
			this.$emit('node-click', e);
		},
		getList() {
			uni.showLoading({
				title: '加载中'
			});
			let trollTre = (array) => {
				for (let i = 0; i < array.length; i++) {
					if (this.selectArr.indexOf(array[i].id) == -1) {
						array[i].choosed = false;
					} else {
						array[i].choosed = true;
					}
					array[i].show = true;
                   
					array[i].half = false;
					if (array[i].children) {
						trollTre(array[i].children);
					}
				}
			};
			if (this.selectType == 1) {
				// 获取人树
				getMembers().then(res => {
					let data = JSON.parse(JSON.stringify(res.data));

					trollTre(data);
					this.data = data;
					this.tree = data;
					this.setHalfStatus(this.tree); 
					uni.hideLoading();
				});
			} else {
				// 获取组树
				getGroups().then(res => {
					let data = JSON.parse(JSON.stringify(res.data));

					trollTre(data);
					this.data = data;
					this.tree = data;  
					uni.hideLoading();
				});
			}
		}
	},
};
</script>
<style lang="scss" scoped>
@keyframes scaleFrames {
    from {
        transform: translateY(110%);
    }

    to {
        transform: translateY(0);
    }
}

.mark {
    width: 100%;
    height: 100vh;
    z-index: 301;
    position: fixed;
    left: 0;
    top: 0;
    background: rgba(0, 0, 0, 0.17);
}

.drawer {
    z-index: 302;
    width: calc(100%);
    margin: 0 auto;
    background-color: #fff;
    border-top-right-radius: 8rpx;
    border-top-left-radius: 8rpx;
    animation: scaleFrames 0.3s ease;
    padding-top: 0rpx;
    position: fixed;
    bottom: 0;
    left: 0;
    letter-spacing: 0.1rpx;

    // padding-bottom: 10rpx;
    // overflow-y: auto;
    .down {
        width: 100%;
        padding: 18rpx 0;

        .down-btn {
            width: 64rpx;
            height: 10rpx;
            background: #d8d8d8;
            border-radius: 6rpx;
            margin: 0 auto;
        }
    }

    &-search {
        width: 710rpx;
        height: 68rpx;
        background: #f6f6f6;
        border-radius: 8rpx;
        margin: 6rpx auto;
        display: flex;
        align-items: center;
        color: #333;

        .left-icon {
            width: 40rpx;
            height: 40rpx;
            padding: 16rpx;
        }

        input {
            flex: 1;
            font-size: 26rpx;
        }

        .clear {
            font-size: 24rpx;
            padding: 16rpx;
        }
    }

    .base-line {
        width: 100%;
        height: 18rpx;
        background-color: #fff;
        border-bottom: 16rpx solid #f3f6f8;
    }

    &-content {
        width: 100%;
        height: 60vh;
        overflow-x: hidden;
        overflow-y: scroll;
        background-color: #f3f6f8;

        &-title {
            width: calc(100% - 20rpx);
            height: 64rpx;
            line-height: 64rpx;
            background: #f3f6f8;
            color: #666666;
            font-size: 24rpx;
            padding-left: 20rpx;
        }

        .raido-item {
            width: calc(100% - 20rpx);
            padding-left: 20rpx;
            height: 72rpx;
            background: #ffffff;
            color: #333333;
            font-size: 28rpx;
            line-height: 72rpx;
        }
    }

    .empty {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 100%;
        margin-top: 100rpx;

        .circle {
            width: 112rpx;
            height: 112rpx;
        }

        image {
            width: 112rpx;
            height: 112rpx;
        }

        .title {
            font-size: 26rpx;
            color: #666;
            font-weight: normal;
            margin-top: 10rpx;
        }
    }
}

.footer-btns {
    display: flex;
    padding: 20rpx 38rpx;
    border-top: 2rpx #eee solid;

    view {
        display: flex;
        flex: 1;
        height: 70rpx;
        justify-content: center;
        align-items: center;
        font-size: 28rpx;
    }

    .reSet {
        background-color: #f5fbff;
        color: #0091ff;
        // margin-right: 10rpx;
        border-top-left-radius: 8rpx;
        border-bottom-left-radius: 8rpx;
    }

    .submit {
        // width: 100%;
        // text-align: center;
        border-top-right-radius: 8rpx;
        border-bottom-right-radius: 8rpx;
        background-color: $theme-color;
        color: #fff;
    }
}
</style>